// QRCodeScannerFragment.kt
package com.example.hanguangfacsemoanaapp

import android.content.Context
import com.journeyapps.barcodescanner.CaptureActivity

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.zxing.integration.android.IntentIntegrator

class QRCodeScannerFragment : Fragment() {

    // 定义一个接口用于回调扫描结果
    interface OnScanResultListener {
        fun onScanResult(result: String)
    }

    // 保存对监听器的引用
    private var listener: OnScanResultListener? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 将Activity强制转换为OnScanResultListener（确保Activity实现了该接口）
        listener = context as? OnScanResultListener
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_qr_code_scanner, container, false)

        // 初始化扫描器
        val integrator = IntentIntegrator(activity)
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
//        integrator.setPrompt("请扫描二维码")
        integrator.setCameraId(1)  // Use a specific camera of the device
        integrator.setBeepEnabled(true)
        integrator.setOrientationLocked(false)

        integrator.setCaptureActivity(CaptureActivity::class.java)

        integrator.initiateScan()

        return view
    }

    override fun onDetach() {
        super.onDetach()
        listener = null
    }
}